package com.nlscan.ncomgateway.core.data.vmfactorary

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import com.nlscan.ble.util.NLogUtil
import com.nlscan.ncomgateway.core.data.repository.DeviceRepository

/**
 * <pre>
 *  author: lin.qing
 *  time  : 2023/3/23
 *  desc  : DeviceXxxViewModel 工厂类，构造参数为 deviceRepository 模板代码
 * </pre>
 * bugFix 前面 device name 为空，会导致这里报错
 */
class DeviceViewModelFactory(private val repository: DeviceRepository) : ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        var viewModel: ViewModel? = null
        var className = modelClass.name
        try {
            //通过反射来生产不同的ViewModel实例
            viewModel = Class.forName(className).getConstructor(DeviceRepository::class.java)
                .newInstance(repository) as ViewModel
        } catch (e: Exception) {
            NLogUtil.e("DeviceViewModelFactory create error! msg: " + e.message)
            e.printStackTrace()
        }
        NLogUtil.i("viewModel is null? : ${viewModel == null}")
        return viewModel as T
    }
}